package com.wenx.v3openfeign.api.fallback;

import com.wenx.v3core.response.R;
import com.wenx.v3openfeign.api.PlatformUserRemoteInfra;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.openfeign.FallbackFactory;
import org.springframework.stereotype.Component;

/**
 * 平台用户远程服务降级工厂
 * 
 * 当平台用户远程服务调用失败时，提供降级处理逻辑
 * 记录错误信息并返回友好的错误响应
 */
@Slf4j
@Component
public class PlatformUserRemoteInfraFallbackFactory implements FallbackFactory<PlatformUserRemoteInfra> {

    @Override
    public PlatformUserRemoteInfra create(Throwable cause) {
        return new PlatformUserRemoteInfra() {
            
            @Override
            public R getPlatformUserAuthInfo(String identifier) {
                return logAndFail("获取平台用户认证信息", "identifier", identifier, cause);
            }

            @Override
            public R getPlatformUserAuthInfoByUsername(String username) {
                return logAndFail("通过用户名获取平台用户认证信息", "username", username, cause);
            }

            @Override
            public R getPlatformUserAuthInfoByEmail(String email) {
                return logAndFail("通过邮箱获取平台用户认证信息", "email", email, cause);
            }

            @Override
            public R getPlatformUserAuthInfoByPhone(String phone) {
                return logAndFail("通过手机号获取平台用户认证信息", "phone", phone, cause);
            }

            @Override
            public R getPlatformUserPermissions(Long userId) {
                return logAndFail("获取平台用户权限", "userId", userId, cause);
            }

            @Override
            public R getPlatformUserRoles(Long userId) {
                return logAndFail("获取平台用户角色", "userId", userId, cause);
            }

            @Override
            public R getPlatformUserMenus(Long userId) {
                return logAndFail("获取平台用户菜单", "userId", userId, cause);
            }

            @Override
            public R isPlatformAccountActive(Long userId) {
                return logAndFail("验证平台用户账户状态", "userId", userId, cause);
            }

            @Override
            public R getPlatformUserAccessibleTenants(Long userId) {
                return logAndFail("获取平台用户可访问租户", "userId", userId, cause);
            }

            @Override
            public R authenticatePlatformUser(String identifier, String password) {
                return logAndFail("平台用户认证", "identifier", identifier, cause);
            }

            /**
             * 记录错误并返回失败响应
             */
            private R logAndFail(String operation, String paramName, Object paramValue, Throwable cause) {
                log.error("平台用户远程服务调用失败: operation={}, {}={}", operation, paramName, paramValue, cause);
                return R.failed("平台用户服务暂时不可用，请稍后重试");
            }
        };
    }
}